package top.mingyi4cjh.cms.common.utils;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import top.mingyi4cjh.cms.common.error.BusinessException;
import top.mingyi4cjh.cms.common.error.EmBusinessError;

import javax.annotation.Resource;
import java.io.*;
import java.util.Objects;

/**
 * @author MingYi
 * @program cms
 * @create 2022/04/27 00:17
 */
@Component
public class FileUtil {
    @Resource
    private FilePathFactory filePathFactory;

    /**
     * 基本文件操作从基础路径。
     */
    public static final String PATH = "./temp/";

    public static File MultipartFileToFile(MultipartFile multipartFile) throws IOException {
        File toFile = null;
        if (!multipartFile.isEmpty()) {
            InputStream ins = multipartFile.getInputStream();
            toFile = new File(Objects.requireNonNull(multipartFile.getOriginalFilename()));
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void deleteTempFile(File file) {
        if (file != null) {
            File delFile = new File(file.toURI());
            delFile.delete();
        }
    }

    public static FileItem getMultipartFile(File file, String fieldName) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

    @Async("Executor")
    public void saveFile(MultipartFile file, String fullFilePath) throws IOException {

        String filePath = filePathFactory.getFilePathByType(file.getContentType());
        File tmp = new File(filePath);
        if (!tmp.exists()) {
            tmp.mkdirs();
        }

        File outFile = new File(fullFilePath);
        FileOutputStream fileOutputStream = new FileOutputStream(outFile);
        InputStream inputStream = file.getInputStream();
        IOUtils.copy(inputStream, fileOutputStream);

        fileOutputStream.flush();
        fileOutputStream.close();
    }

    /**
     * 删除文件
     *
     * @param fileName 文件名
     * @return 删除是否成功信息
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(PATH + fileName);
        if (file.isFile() && file.exists()) {
            return file.delete();
        } else {
            return false;
        }
    }
}

